package de.wwi11b2.mjp.comicvineclient;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends Activity implements DatabaseFragment.OnFragmentInteractionListener {

	private String[] menuItems = null;
    private ListView menu = null;

    private ArrayList<Item> charaItems;

    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
        menuItems = getResources().getStringArray(R.array.menu_items);
        menu = (ListView) findViewById(R.id.left_drawer);
        menu.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, menuItems));
        menu.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                // ListView Clicked item index
                int itemPosition     = position;

                // ListView Clicked item value
                String  itemValue    = (String) menu.getItemAtPosition(position);

                // Show Alert
                Toast.makeText(getApplicationContext(),
                        "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG)
                        .show();

            }

        });
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        DatabaseFragment fragment = DatabaseFragment.newInstance(getCharaItems());
        fragmentTransaction.add(R.id.content_frame, fragment);
        fragmentTransaction.commit();
    }

    @Override
    public void onFragmentInteraction(Item item) {
        Toast.makeText(getApplicationContext(),
                "OnFragmentInteraction called! Item: " + item.getName(), Toast.LENGTH_LONG)
                .show();
    }

    public ArrayList<Item> getCharaItems() {
        if(charaItems == null){
            charaItems = new ArrayList<Item>((new DataHelper(getApplicationContext()).findAll(Item.ResourceType.CHARACTER.ordinal())));
        }
        return charaItems;
    }
}
